﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Net;
using System.IO;

namespace RadarMonitor.FTPMonitor
{
    public class FTPMonitor
    {

        private bool EmptyFolderFlag = false; // FTP文件夹为空标志

        public FTPMonitor(string ftpUri,string user, string password)
        {
            FTPUri = ftpUri;
            FTPUser = user;
            FTPPassword = password;
        }

        // 雷达数据传正常
        public event Action<string> RadarDataTransmissionSuccessed;
        // 雷达数据传输延时报警 事件
        public event Action<DateTime?,string> RadarDataTransmissionTimeoutEvent;
        // FTP 访问失败事件 
        public event Action<Exception> FTPAccessFailedEvent;
        
        // FTP 文件夹地址
        public string FTPUri { get; set; } = "ftp://10.76.31.234/radar/realtime/fmt/Z9631/";
        // 用户名
        public string FTPUser { get; set; } = "Data_reader";
        // 密码
        public string FTPPassword { get; set; } = "Data_reader1";
        // 查询间隔（单位秒）
        public int QueryInterval { get; set; } = 10*60;
        // 报警间隔（单位秒）：多久数据没更新触发报警
        public int AlarmInterval { get; set; } = 18 * 60;

        private Timer loopTimer = null;

        internal void Start()
        {
            if (loopTimer != null)
                return;
            Console.WriteLine($"FTP Monitor:{FTPUri} {QueryInterval} {AlarmInterval}");
            loopTimer = new Timer(CheckLoop, null, 0, QueryInterval * 1000);
        }

        internal void Stop()
        {
            loopTimer?.Dispose();
            loopTimer = null;

        }

        public void CheckLoop(object info)
        {
            try
            {

                //Create FTP request
                var suffer =  DateTime.UtcNow.ToString("yyyy/MM/dd");
                FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(FTPUri + suffer); //"ftp://127.0.0.1/data/"

                request.Method = WebRequestMethods.Ftp.ListDirectory;
                request.Credentials = new NetworkCredential(FTPUser, FTPPassword); //"test", "12345"
                request.UsePassive = true;
                request.UseBinary = true;
                request.KeepAlive = false;
                request.Timeout = 6000;

                FtpWebResponse response = (FtpWebResponse)request.GetResponse();
                Stream responseStream = response.GetResponseStream();
                StreamReader reader = new StreamReader(responseStream);

                // 找出最新的时间 和 文件      
                DateTime latest = DateTime.MinValue;
                string lasetFile = null;
                while (!reader.EndOfStream)
                {
                    var file = reader.ReadLine();
                    string[] sep = new string[] { "_" };
                    var arr = file.Split(sep, StringSplitOptions.RemoveEmptyEntries);
                    if(arr.Length >= 5)
                    {
                        System.Diagnostics.Debug.WriteLine("FTP Response:" + file);
                        string dateStr = arr[4];
                        try
                        {
                            var date = DateTime.ParseExact(dateStr, "yyyyMMddHHmmss", System.Globalization.CultureInfo.InvariantCulture);
                            if (date > latest)
                            {
                                latest = date;
                                lasetFile = file;
                            }
                        }
                        catch { } 
                    }
                }

                //Clean-up
                reader.Close();
                responseStream.Close(); //redundant
                response.Close();

                if (lasetFile ==null ) 
                {
                    if (EmptyFolderFlag) // 连续2次读取到空文件夹
                    {
                        RadarDataTransmissionTimeoutEvent?.Invoke(null, null);
                    }
                    else // 读到空文件夹
                    {}
                }
                else
                {
                    DateTime now = DateTime.UtcNow;
                    var timeSpan = now - latest;
                    double interval = Math.Abs(timeSpan.TotalSeconds);
                    if (interval < AlarmInterval) //报警
                    {
                        RadarDataTransmissionSuccessed?.Invoke(lasetFile);
                    }
                    else
                    {
                        RadarDataTransmissionTimeoutEvent(latest, lasetFile);
                    }
                }
                EmptyFolderFlag = lasetFile == null;
            }
            catch (Exception e)
            {
                FTPAccessFailedEvent?.Invoke(e);
            }
        }

        public  void ChangeSettings(string uri, int checkInterval, int alarmInterval)
        {
            if (uri != null)
                FTPUri = uri;
            this.AlarmInterval = alarmInterval;

            if(checkInterval != QueryInterval)
            {
                QueryInterval = checkInterval;
                try
                {
                    loopTimer?.Change(0, QueryInterval*1000);
                }
                catch (Exception)
                {}
            }
        }
    }
}
